package org.particlethink.service.listen.listener;

import org.particlethink.entry.PlanStatus;
import org.particlethink.entry.PlanTyp;
import org.particlethink.mapper.BatchPlanMapper;
import org.particlethink.mapper.MasterPlanMapper;
import org.particlethink.mapper.PlanMaterialMapper;
import org.particlethink.model.BatchPlan;
import org.particlethink.model.MasterPlan;
import org.particlethink.model.PlanMaterial;
import org.particlethink.service.listen.event.SubmitBatchPlanEvent;
import org.particlethink.utils.ListUtilsKt;
import org.particlethink.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 提交批次计划更新总计划规划率
 */

@Component
public class UpdateMasterPlanPlanningRateListener implements ApplicationListener<SubmitBatchPlanEvent> {

    @Autowired
    private BatchPlanMapper batchPlanMapper;

    @Autowired
    private MasterPlanMapper masterPlanMapper;

    @Autowired
    private PlanMaterialMapper planMaterialMapper;

    @Override
    public void onApplicationEvent(SubmitBatchPlanEvent event) {
        Integer masterPlanId = event.getMasterPlanId();
        if (masterPlanId == null || masterPlanId <= 0) {
            return;
        }

        MasterPlan masterPlan = masterPlanMapper.selectByPrimaryKey(masterPlanId);
        if (masterPlan==null){
            return;
        }
        List<PlanMaterial> masterPlanMaterials = planMaterialMapper.selectByPlanIDAndTyp(masterPlan.getId(), PlanTyp.Master);

        List<BatchPlan> batchPlans = batchPlanMapper.selectAllByMasterPlanIDAndStatus(masterPlanId, PlanStatus.Submitted);
        List<PlanMaterial> batchPlanMaterials = planMaterialMapper.selectByPlanIDsAndTyp(batchPlans.stream().map(BatchPlan::getId).collect(Collectors.toList()), PlanTyp.Batch);


        Map<Integer, List<PlanMaterial>> materialID2PlanMaterialsMap = batchPlanMaterials.stream().collect(Collectors.groupingBy(PlanMaterial::getMaterialId));
        masterPlanMaterials.forEach(planMaterial -> {
            if (!materialID2PlanMaterialsMap.containsKey(planMaterial.getMaterialId())) {
                return;
            }

            List<PlanMaterial> planMaterials = materialID2PlanMaterialsMap.get(planMaterial.getMaterialId());

            Integer reduce = ListUtilsKt.reduce(planMaterials, 0, (res, plan) -> {
                return res + plan.getExpectNum();
            });
            planMaterial.setActualNum(reduce);
        });

        masterPlan.setBatchPlanCount(batchPlans.size());
        masterPlanMapper.updateByPrimaryKey(masterPlan);
        if (masterPlanMaterials.isEmpty()) {
            return;
        }
        planMaterialMapper.updateActualNum(masterPlanMaterials);
    }
}
